package com.guli.gulimall.member.service.impl;

import com.guli.common.utils.R;
import com.guli.gulimall.member.dao.MemberLevelDao;
import com.guli.gulimall.member.entity.MemberLevelEntity;
import com.guli.gulimall.member.exception.PhoneExistException;
import com.guli.gulimall.member.exception.UsernameExistException;
import com.guli.gulimall.member.vo.MemberLoginVo;
import com.guli.gulimall.member.vo.MemberRegistVo;
import com.guli.gulimall.member.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.member.dao.MemberDao;
import com.guli.gulimall.member.entity.MemberEntity;
import com.guli.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        //设置默认等级
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名和手机是否唯一,预先检查，异常会抛出错误
        checkPhoneUnique(memberRegistVo.getPhone());
        checkUsernameUnique(memberRegistVo.getUserName());
        //手机号
        memberEntity.setMobile(memberRegistVo.getPhone());
        //用户名
        memberEntity.setUsername(memberRegistVo.getUserName());
        //密码，spring 加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePwd = bCryptPasswordEncoder.encode(memberRegistVo.getPassword());
        memberEntity.setPassword(encodePwd);
        //todo 其他的默认信息,后续再做补充
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String loginAccount = loginVo.getLoginAccount();
        String password = loginVo.getPassword();
        //1.去数据库查询用户 SELECT * FROM `ums_member` WHERE username=? OR mobile=?
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccount).or().eq("mobile", loginAccount));
        if (memberEntity == null) {
            //登录失败
            return null;
        } else {
            //1.获取到数据库查出来的加密密码
            String dbpassword = memberEntity.getPassword();
            //2.对比密码
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, dbpassword);
            if (matches) {
                //登录成功
                return memberEntity;
            } else {
                //密码错误
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();
        //1.判断当前社交用户是否登录过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //已经注册过，更新社交帐号数据
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            //更新
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //注册
            MemberEntity regist = new MemberEntity();
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            regist.setNickname(socialUser.getNick_name());
            regist.setSocialUid(socialUser.getUid());
            regist.setCreateTime(new Date());
            this.baseMapper.insert(regist);
            return regist;
        }
    }

}